﻿/*
Config Example : 
{ 
    locationCode: '@ViewBag.Location', 
    subKey: '@ViewBag.SubKey', 
    addButtonName:'btnGuestbookAdd', 
    isAjaxCall:true, 
    isUseSecret : false 
    pageSize:10
}
*/

var guestbookLib = function (config) {
    
    var locationCode = config.locationCode;
    var subKey = config.subKey;
    var addButtonName = config.addButtonName || "btnAdd";
    var isAjaxCall = config.isAjaxCall === undefined ? false : true;
    var isUseSecret = config.isUseSecret === undefined ? true : false;
    var pageSize = config.pageSize === undefined || isNaN(config.pageSize) ? 10 : config.pageSize;
    var chapcharval = 0;
    
    $(document).ready(function () {
        
        if (!isUseSecret) {
            $("#chkIsPrivate").parent().hide();
            $("#lblSecretMessage").hide();
        }

        if (isAjaxCall) {
            $.ajax({
                type: "GET",
                async: false,
                url: "/GuestBook/list?location=" + locationCode + "&subKey=" + subKey + "&pageSize=" + pageSize,
                datatype: 'json',
                traditional: true,
                success: function (data) {
                    if (data.GuestBookList && data.GuestBookList.length > 0) {

                        // 데이터 배열을 받아 HTML를 렌더링 한다.
                        for (var i = 0; i < data.GuestBookList.length; i++) {
                            var temp = $("#guestBookAjaxMaster").html();

                            var html = temp.replace(/##GuestName##/gi, data.GuestBookList[i].GuestName)
                                .replace(/##InsertDate##/gi, data.GuestBookList[i].InsertDateString)
                                .replace(/##Comment##/gi, data.GuestBookList[i].Comment)
                                .replace(/##Idx##/gi, data.GuestBookList[i].Idx)
                                .replace(/##PrivateType##/gi, data.GuestBookList[i].IsPrivate ? "secret" : "general");

                            $("#divGuestBookList").append(html);

                            // 댓글별 답글을 렌더링 한다.
                            for (var j = 0; j < data.GuestBookList[i].ReplyList.length; j++) {
                                var detailTemp = $("#guestBookDetail").html();

                                var detailHtml = detailTemp.replace(/##GuestName##/gi, data.GuestBookList[i].ReplyList[j].GuestName)
                                    .replace(/##InsertDate##/gi, data.GuestBookList[i].ReplyList[j].InsertDateString)
                                    .replace(/##Comment##/gi, data.GuestBookList[i].ReplyList[j].Comment);

                                $("#divDetailList_" + data.GuestBookList[i].Idx).append(detailHtml);
                            }
                        }

                        $("#hidLastGuestBookIdx").val(data.LastIdx);
                    } else {
                        
                    }
                },
                beforeSend: function () {
                    //showLoadingLayer();
                },
                complete: function () {
                    //hideLoadingLayer();
                },
                error: function (xhr, status, error) {

                }
            });
        }

        // 마우스 Scroll 시 글 더보기

        $(window).scroll(function () {
            if ($(window).scrollTop() == $(document).height() - $(window).height()) {
                if ($("#hidLastGuestBookIdx").val() > 0) {
                    $.ajax({
                        type: "GET",
                        async: false,
                        url: "/GuestBook/more?location=" + locationCode + "&subKey=" + subKey + "&firstIdx=" + $("#hidLastGuestBookIdx").val() + "&pageSize=10",
                        datatype: 'json',
                        traditional: true,
                        success: function (data) {
                            if (data.GuestBookList && data.GuestBookList.length > 0) {

                                // 데이터 배열을 받아 HTML를 렌더링 한다.
                                for (var i = 0; i < data.GuestBookList.length; i++) {
                                    var temp = $("#guestBookAjaxMaster").html();

                                    var html = temp.replace(/##GuestName##/gi, data.GuestBookList[i].GuestName)
                                        .replace(/##InsertDate##/gi, data.GuestBookList[i].InsertDateString)
                                        .replace(/##Comment##/gi, data.GuestBookList[i].Comment)
                                        .replace(/##Idx##/gi, data.GuestBookList[i].Idx)
                                        .replace(/##PrivateType##/gi, data.GuestBookList[i].IsPrivate ? "secret" : "general");

                                    $("#divGuestBookList").append(html);

                                    // 댓글별 답글을 렌더링 한다.
                                    for (var j = 0; j < data.GuestBookList[i].ReplyList.length; j++) {
                                        var detailTemp = $("#guestBookDetail").html();

                                        var detailHtml = detailTemp.replace(/##GuestName##/gi, data.GuestBookList[i].ReplyList[j].GuestName)
                                            .replace(/##InsertDate##/gi, data.GuestBookList[i].ReplyList[j].InsertDateString)
                                            .replace(/##Comment##/gi, data.GuestBookList[i].ReplyList[j].Comment);

                                        $("#divDetailList_" + data.GuestBookList[i].Idx).append(detailHtml);
                                    }
                                }

                                $("#hidLastGuestBookIdx").val(data.LastIdx);

                            } else {

                            }
                        },
                        beforeSend: function () {
                            //showLoadingLayer();
                        },
                        complete: function () {
                            //hideLoadingLayer();
                        },
                        error: function (xhr, status, error) {

                        }
                    });
                }
            }
        });


        $("#" + addButtonName).on("click", function () {
            // 사용자 편의를 위해 쿠키에 저장된 이름을 이름 inputBox에 바인딩 한다.
            var name = getCookie("guestName");

            if (name) {
                $("#txtWriterName").val(name);
                $("#txtReplyName").val(name);
            }

            // 캡차 설정
            $.ajax({
                type: "GET",
                async: false,
                url: "/GuestBook/GetCapchaString",
                datatype: 'json',
                traditional: true,
                success: function (data) {
                    if (data.CapchaString) {
                        chapcharval = data.CapchaString;
                    } else {
                        chapcharval = 0;
                    }

                    var firstKey = Math.floor((Math.random() * chapcharval) + 1);
                    var secondKey = chapcharval - firstKey;

                    $("#chpch1").html(firstKey);
                    $("#chpch2").html(secondKey);
                    $("#chpRech1").html(firstKey);
                    $("#chpRech2").html(secondKey);
                    /* Chatchar Val 영역 설정 */

                    $("#divGuestBookWriteArea").modal("show");
                },
                beforeSend: function () {
                    //showLoadingLayer();
                },
                complete: function () {
                    //hideLoadingLayer();
                },
                error: function (xhr, status, error) {

                }
            });
        });

        $("#btnGuestbookSave").on("click", function () {
            if ($("#txtWriterName").val() == "") {
                return bootbox.alert("이름을 입력해주세요.");
            }

            if ($("#txtComment").val() == "") {
                return bootbox.alert("댓글 내용을 입력해 주세요.");
            }

            if ($("#txtChpchVal").val() != chapcharval) {
                return bootbox.alert("문제의 정답을 맞춰주세요. 정답은 " + chapcharval + "!!");
            }

            var isPrivateVal = $("#chkIsPrivate").is(":checked");

            if (isPrivateVal) {
                //if ($("#txtContract").val() == "") return alert("비밀글은 반드시 연락처를 입력하여야 합니다.");
                //if (!confirm("비밀글로 등록하시면 방명록에 보이지 않으며, \r\n등록하신 연락처로 주인장이 답변을 드립니다. \r\n등록하시겠습니까?")) return false;
                if (!confirm("등록후엔 운영자외 수정/삭제가 불가합니다. 등록하시겠습니까?")) return false;
            } else {
                if (!confirm("등록후엔 운영자외 수정/삭제가 불가합니다. 등록하시겠습니까?")) return false;
            }

            saveContent();

            return false;
        });

        $("#btnGuestbookReSave").on("click", function () {
            if ($("#txtReplyName").val() == "") {
                return alert("이름을 입력해주세요.");
            }

            if ($("#txtReplyComment").val() == "") {
                return alert("댓글 내용을 입력해 주세요.");
            }

            if ($("#txtReChpchVal").val() != chapcharval) {
                return alert("문제의 정답을 맞춰주세요. 정답은 " + chapcharval + "!!");
            }

            saveReplyContent($("#divReplyArea").attr("data-ParentIdx"));

            return false;
        });

        $("#chkIsPrivate").on("click", function () {
            if ($(this).is(":checked")) {
                $("#divContract").show();
            } else {
                $("#divContract").hide();
            }
        });

        function saveContent() {
            var nameVal = htmlEscape(removeSpCharRegx($("#txtWriterName").val()));
            var commentVal = htmlEscape(removeSpCharRegx($("#txtComment").val()));
            var isPrivateVal = $("#chkIsPrivate").is(":checked");
            var contractVal = htmlEscape(removeSpCharRegx($("#txtContract").val()));
            var captchaVal = htmlEscape(removeSpCharRegx($("#txtChpchVal").val()));
            
            $.ajax({
                type: "POST",
                async: true,
                url: "/GuestBook/Create",
                data: { LocationCode: locationCode, SubKey: subKey, GuestName: nameVal, Comment: commentVal, IsPrivate: isPrivateVal, SecureEmailAddress: contractVal, CaptcharResponse: captchaVal },
                datatype: 'json',
                traditional: true,
                success: function (data) {
                    if (data.GuestBookData) {
                        /* Show MessageBox */
                        bootbox.alert("등록되었습니다.");

                        /* Create New Row Html And Append */
                        if (!data.GuestBookData.IsPrivate) {
                            var temp = $("#guestBookAjaxMaster").html();

                            var html = temp.replace(/##GuestName##/gi, data.GuestBookData.GuestName)
                                .replace(/##InsertDate##/gi, data.GuestBookData.InsertDateString)
                                .replace(/##Comment##/gi, data.GuestBookData.Comment)
                                .replace(/##Idx##/gi, data.GuestBookData.Idx)
                                .replace(/##PrivateType##/gi, data.GuestBookData.IsPrivate ? "secret" : "general");

                            $("#divGuestBookList").children().eq(0).before(html);
                        }

                        /* hide save Modal */
                        $("#divGuestBookWriteArea").modal("hide");
                    }
                    else if (data.InvalidCaptcha) {
                        bootbox.alert("잘못된 Captcha 값을 입력하였습니다..", function () { });
                    }
                    else {
                        bootbox.alert("등록에 실패하였습니다.", function () { console.log(error); });
                    }
                },
                beforeSend: function () {
                    //showLoadingLayer();
                },
                complete: function () {
                    setCookie("guestName", nameVal);
                    $("#txtComment").val("");
                    $("#txtChpchVal").val("");
                },
                error: function (xhr, status, error) {
                    bootbox.alert("예기치 않은 에러가 발생하였습니다.", function () { console.log(error); });
                }
            });
        }

        function saveReplyContent(parentIdx) {
            var nameVal = htmlEscape(removeSpCharRegx($("#txtReplyName").val()));
            var commentVal = htmlEscape(removeSpCharRegx($("#txtReplyComment").val()));
            var captchaVal = htmlEscape(removeSpCharRegx($("#txtReChpchVal").val()));

            $.ajax({
                type: "POST",
                async: true,
                url: "/GuestBook/AddReply",
                data: { LocationCode: locationCode, SubKey: subKey, ParentIdx: parentIdx, GuestName: nameVal, Comment: commentVal, CaptcharResponse: captchaVal },
                datatype: 'json',
                traditional: true,
                success: function (data) {
                    if (data.ReplyData) {
                        /* Show MessageBox */
                        bootbox.alert("등록되었습니다.");

                        /* Create New Row Html And Append */
                        var temp = $("#guestBookDetail").html();

                        var html = temp.replace(/##GuestName##/gi, data.ReplyData.GuestName)
                            .replace(/##InsertDate##/gi, data.ReplyData.InsertDateString)
                            .replace(/##Comment##/gi, data.ReplyData.Comment);

                        $("#divDetailList_" + parentIdx).append(html);

                        /* hide save Modal */
                        $("#divReplyArea").modal("hide");

                    }
                    else if (data.InvalidCaptcha) {
                        bootbox.alert("잘못된 Captcha 값을 입력하였습니다..", function () { });
                    }
                    else {
                        bootbox.alert("등록에 실패하였습니다.", function () { console.log(error); });
                    }
                },
                beforeSend: function () {
                    //showLoadingLayer();
                },
                complete: function () {
                    setCookie("guestName", nameVal);
                    $("#txtReplyComment").val("");
                    $("#txtReChpchVal").val("");
                },
                error: function (xhr, status, error) {
                    bootbox.alert("예기치 않은 에러가 발생하였습니다.", function () { console.log(error); });
                }
            });
        }
    });

    window.saveReply = function (idx) {

        // 사용자 편의를 위해 쿠키에 저장된 이름을 이름 inputBox에 바인딩 한다.
        var name = getCookie("guestName");

        if (name) {
            $("#txtWriterName").val(name);
            $("#txtReplyName").val(name);
        }

        // 캡차 설정
        $.ajax({
            type: "GET",
            async: false,
            url: "/GuestBook/GetCapchaString",
            datatype: 'json',
            traditional: true,
            success: function (data) {
                if (data.CapchaString) {
                    chapcharval = data.CapchaString;
                } else {
                    chapcharval = 0;
                }

                var firstKey = Math.floor((Math.random() * chapcharval) + 1);
                var secondKey = chapcharval - firstKey;

                $("#chpch1").html(firstKey);
                $("#chpch2").html(secondKey);
                $("#chpRech1").html(firstKey);
                $("#chpRech2").html(secondKey);
                /* Chatchar Val 영역 설정 */

                $("#divReplyArea").attr("data-ParentIdx", idx);
                $("#divReplyArea").modal("show");
            },
            beforeSend: function () {
                //showLoadingLayer();
            },
            complete: function () {
                //hideLoadingLayer();
            },
            error: function (xhr, status, error) {

            }
        });

        return this;
    }
};